package com.echoesnet.echoesshortvideo.Fragments;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;

import com.baidu.mobstat.StatService;
import com.orhanobut.logger.Logger;

import java.util.Arrays;
import java.util.List;

/**
 * @author yqh
 * @Date 2018/4/23
 * @Version 1.0
 * <p>
 * <p>
 * LazyFragment 来自tab切换的包；如果替换为v4 Fragment影响首页tab
 * 主要是 --
 * 懒加载Fragment / 只有创建并显示的时候才会调用onCreateViewLazy方法
 */
public abstract class BaseFragment extends Fragment
{
    private final String TAG = BaseFragment.class.getSimpleName();
    private List<String> notStatPages =
            Arrays.asList(new String[]{});
    private volatile int hasStat = 0;//当前是否存在一个统计状态
    private volatile boolean isPageVisible = false;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onResume()
    {
        super.onResume();
        Logger.t(TAG).d("onResume>" + getPageName());
        if (notStatPages.contains(getPageName()))
            return;
        if (hasStat == 0 && isPageVisible)
        {
            Logger.t(TAG).d("onResume>onPageStart>" + getPageName());
            StatService.onPageStart(getActivity(), getPageName());
            hasStat++;
        }
    }

    @Override
    public void onPause()
    {
        super.onPause();
        //Logger.t(TAG).d("onPause>" + getPageName());
        if (notStatPages.contains(getPageName()))
            return;
        if (hasStat >= 1 && isPageVisible)
        {
            //Logger.t(TAG).d("onPause>onPageEnd>" + getPageName());
            StatService.onPageEnd(getActivity(), getPageName());
            hasStat--;
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser)//不能确定它的执行顺序--wb
    {
        super.setUserVisibleHint(isVisibleToUser);
        isPageVisible = isVisibleToUser;
        Logger.t(TAG).d("设置可见性》" + isPageVisible + " hasStat> " + hasStat);
        if (isVisibleToUser)
        {
            if (hasStat == 0)
            {
                Logger.t(TAG).d("setUserVisibleHint>onPageStart>" + getPageName());
                StatService.onPageStart(getActivity(), getPageName());
                hasStat++;
            }
        }
        else
        {
            if (hasStat >= 1)
            {
                Logger.t(TAG).d("setUserVisibleHint>onPageEnd>" + getPageName());
                StatService.onPageEnd(getActivity(), getPageName());
                hasStat--;
            }
        }
    }

    protected abstract String getPageName();

}
